﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MetaCollection.Framework;
using MetaCollection.Framework.Model;
using MetaCollection.ContentService.Http;

namespace MetaCollection.ContentService.WebDav.Methods
{
	/// <summary>
	/// This controller serves request for HEAD information on an item.  These
	/// type of requests typically are looking for last modified and cache type
	/// information.
	/// 
	/// All headers returned in a GET request must be returned in a HEAD request.
	/// </summary>
	public static class Head
	{
		/// <summary>
		/// Does the process request.
		/// </summary>
		/// <param name="context">The context.</param>
		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "handler", Justification = "Standard method signature, static classes can't implement interfaces.")]
		public static void Respond(DavContext context, IRequestHandler handler)
		{
			IItemInstance item = context.Item as IItemInstance;
			Http.HttpMethods supported = (Http.HttpMethods)context.SupportedMethods;

			context.Response.SetItemHeaders(item, HttpCacheability.Server);

			if (supported.IsSet(Http.HttpMethods.Get | Http.HttpMethods.Head | Http.HttpMethods.Options | Http.HttpMethods.Put | Http.HttpMethods.PropFind | Http.HttpMethods.PropPatch))
			{
				context.Response.Headers.Add("DAV", "1, 2");
				context.Response.Headers.Add("MS-Author-Via", "DAV");
				context.Response.Headers.Add("DocumentManagementServer", "Properties Schema;Source Control;Version History;");
				context.Response.Headers.Add("X-MSDAVEXT", "1");
			}

			if (supported.IsSet(Http.HttpMethods.VersionControl))
				context.Response.Headers.Add("Versioning-Support", "DAV:basicversioning");
			if (supported.IsSet(Http.HttpMethods.Search))
				context.Response.Headers.Add("DASL", "<DAV:basicsearch>");

			context.Response.Headers.Add("Accept-Ranges", "bytes");
			context.Response.Headers.Add("Allow", supported.ToString().ToUpperInvariant());
			if (!context.Request.IsModifiedSinceLastRequest(item))
				return;

			context.Response.SetStatus((int)SuccessStatus.Ok, "OK");
		}
	}
}
